package com.ymm.system.core.utils;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;

/**
 * @Description: MD5加密工具类
 * @Author: Xuecheng Li
 * @CreateTime: 2022-08-04 09:33
 * @Version: 1.0.0
 */
@Slf4j
public final class EncryptionUtils {

    /**
     * @Description 密码加密
     * @Param [password]：密码
     * @return String
     **/
    public static String encryption(String password){
        log.info("输入加密字符串：{}", password);
        try {
            char hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
                    '9', 'a', 'b', 'c', 'd', 'e', 'f' };
            byte[] bytes = password.getBytes();
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes);
            bytes = md.digest();
            int j = bytes.length;
            char[] chars = new char[j * 2];
            int k = 0;
            for (int i = 0; i < bytes.length; i++) {
                byte b = bytes[i];
                chars[k++] = hexChars[b >>> 4 & 0xf];
                chars[k++] = hexChars[b & 0xf];
            }
            return new String(chars);
        } catch (Exception e) {
            log.error("输入为{}", e.getMessage());
            throw new RuntimeException("MD5加密出错！！");
        }
    }

    public static void main(String[] args) {

        // 测试输入为空字符串情况
        String test1 = "";
        System.out.println(EncryptionUtils.encryption(test1));

        // 测试数字情况
        String test2 = "1234";
        System.out.println(EncryptionUtils.encryption(test2));

        // 测试一般情况
        String test3 = "1234@abc";
        System.out.println(EncryptionUtils.encryption(test3));

        // 测试null情况
        System.out.println(EncryptionUtils.encryption(null));

    }
}
